import { getImageDomain,getMapKey } from '@/common/request/api'
import { setLocale } from '@/common/init/i18n'
import {useGlobal,useInit,type BaseVariable} from '@/common/stores'
import {mapInit} from '@/common/utils/map'

type CB = () => void

class Dispatcher {
	// 初始化的请求是否完成
	isRequestComplete = false
	// app初始化是否完成，完成代表可调用pinia存储相关的初始化变量
	isAppInitComplete = false
	dispCbs:Array<CB> = []
	on (cb:CB) {
		// 初始化的请求已经完成，直接回调
		if(this.isRequestComplete){
			cb()
		}else{
			// 未完成则存入队列中，待初始化的请求完成后统一回调
			this.dispCbs.push(cb)
		}
	}
	//初始化的请求已经完成
	requestComplete (cb?:CB) {
		this.isRequestComplete = true
		cb&&this.dispCbs.unshift(cb)
		this.checkCompleteStatus()
	}
	// app已进入onLaunch生命周期，可以发送http请求
	appInitComplete () {
		this.isAppInitComplete = true
		this.checkCompleteStatus()
	}
	// 检查是否可以执行初始化的请求队列
	checkCompleteStatus () {
		
		if(this.isRequestComplete && this.isAppInitComplete){
			this.dispCbs.forEach(item => item())
		}
	}
}

export const baseInitDispatcher = new Dispatcher()

const init = async () => {
	// 获取图片域名、多语言、货币单位配置
	let res = await getImageDomain()
	let baseVariable:BaseVariable = {
		unitEn:'￥',
		countryCode:'zh_CN',
		host:'',
	}
	let countryCode = uni.getStorageSync('locale')
	if (res.siteCurrency) baseVariable.unitEn = res.siteCurrency
	if (res.siteClient&&!countryCode) countryCode = res.siteClient
	baseVariable.host = res.host
	
	baseVariable.countryCode = countryCode||'zh_CN'
	setLocale(baseVariable.countryCode)
	// 地图初始化
	let mapRes = await mapInit()
	if(mapRes?.data?.key?.length){
		useInit().setHasMapKey(true)
	}
	useGlobal().setGlobal(baseVariable)
	// baseInitDispatcher.requestComplete(() => {
		
	// })
	
	
}
export default init